#include "recbox.h"
#include "ui_recbox.h"
#include"recboxitem.h"
#include<QJsonArray>
#include<QJsonObject>
RecBox::RecBox(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RecBox),row(1),col(4)
{
    ui->setupUi(this);

}

RecBox::~RecBox()
{
    delete ui;
}

void RecBox::initRecBoxUI(QJsonArray arry, int row)
{
    if(row == 2)
    {
        //说明有两行；
        this->col = 8;
        this->row = 2;
    }
    else if(row == 1)
    {
        //隐藏downlayout；
       ui->recDown->hide();
    }
    count = arry.size()/col;
    currentIndex = 0;
    jsArry = arry;
    createRecBoxItem(arry);
}

void RecBox::createRecBoxItem(QJsonArray arry)
{
    int n = 0;
    for(int i =currentIndex*col;i<col+col*currentIndex;i++)
    {
        //创建RecBoxItem对象；
        RecBoxItem*item = new RecBoxItem(this);
        QJsonObject obj = arry[i].toObject();
        item->setImage(obj["path"].toString());
        item->setRecText(obj["text"].toString());
        if(n>=col/2&&row == 2)
        {
            ui->down->addWidget(item);
        }
        else
        {
            ui->up->addWidget(item);
        }
        n++;

    }
}




void RecBox::on_btLeft_clicked()
{
    //在点击前需要删除以前创建的item;
    QList<RecBoxItem*>list = ui->recUp->findChildren<RecBoxItem*>();
    for(auto e:list)
    {
        ui->up->removeWidget(e);
        delete e;
    }
    QList<RecBoxItem*>listdown = ui->recDown->findChildren<RecBoxItem*>();
    for(auto e:listdown)
    {
        ui->down->removeWidget(e);
        delete e;
    }
    currentIndex--;
    if(currentIndex<0)
    {
        currentIndex = count - 1;
    }
    createRecBoxItem(jsArry);
}

void RecBox::on_btRight_clicked()
{
    QList<RecBoxItem*>list = ui->recUp->findChildren<RecBoxItem*>();
    for(auto e:list)
    {
        ui->up->removeWidget(e);
        delete e;
    }
    QList<RecBoxItem*>listdown = ui->recDown->findChildren<RecBoxItem*>();
    for(auto e:listdown)
    {
        ui->down->removeWidget(e);
        delete e;
    }
    currentIndex++;
    currentIndex%=count;
    createRecBoxItem(jsArry);
}
